package com.yami.shop.api.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.dto.FriendDTO;
import com.yami.shop.bean.dto.FriendSaveDTO;
import com.yami.shop.bean.model.MeltCloudUserRemark;
import com.yami.shop.bean.model.NotifyLog;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserSecurityConfig;
import com.yami.shop.bean.vo.MyFriendVo;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.service.FriendService;
import com.yami.shop.service.MeltCloudUserRemarkService;
import com.yami.shop.service.NotifyLogService;
import com.yami.shop.service.UserSecurityConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.yami.shop.common.response.ServerResponseEntity.success;

@RestController
@RequestMapping("/friend")
@Tag(description = "好友关系", name = "好友关系")
public class FriendController {

    @Autowired
    private FriendService friendService;
    @Autowired
    private NotifyLogService notifyLogService;
    @Autowired
    private UserSecurityConfigService userSecurityConfigService;
    @Autowired
    private MeltCloudUserRemarkService userRemarkService;

    @PostMapping("/follow")
    @Operation(summary =  "新增关注")
    public ServerResponseEntity follow(@RequestBody @Valid FriendSaveDTO friend) {
        if(friend.getFriendId().equals(friend.getUserId())){
           return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.sys.illegalArgument"));
        }
        friendService.follow(friend);
        return success();
    }

    @PostMapping("/list")
    @Operation(summary =  "我的粉丝列表", description = "我的粉丝列表")
    public ServerResponseEntity<List<MyFriendVo>> list(@RequestBody FriendDTO friendDTO) {
        List<MyFriendVo> list = friendService.firendList(friendDTO.getUserId(),friendDTO.getUserName());
        return success(list);
    }


    @GetMapping("/newConcernsList/{userId}")
    @Operation(summary =  "新增关注列表", description = "新增关注列表")
    public ServerResponseEntity<List<MyFriendVo>> newConcernsList(@PathVariable("userId")String userId) {
        List<MyFriendVo> list = friendService.newConcernsList(userId);
        return success(list);
    }


    @GetMapping("/getFansFollowNum")
    @Operation(summary =  "关注数量", description = "关注数量")
    public ServerResponseEntity<Map<String, Object>> getFansFollowNum(@RequestParam String usId) {
        Map<String, Object> map = friendService.selectFansFollowNum(usId);
        return ServerResponseEntity.success(map);
    }

    /**
     *
     * @param usId 访友id
     * @param currentId 当前用户id
     * @return
     */
    @GetMapping("/ua/gethome")
    @Operation(summary =  "主页",description = "followNum: 关注数 fansNum：粉丝数 nickName：名称 pic：图像 real:0未实名1已实名 ")
    public ServerResponseEntity<Map<String, Object>> gethome(@RequestParam String usId,@RequestParam String currentId) {
        Map<String, Object> map = friendService.gethome(usId,currentId);
        return ServerResponseEntity.success(map);
    }

    /**
     *
     * @param page 刷新位的消息
     * @param usId 为空代表用户自己的粉丝列表 不为空代表 当前访问用户的粉丝列表
     * @param currentId
     * @return
     */
    @GetMapping("/fansPage")
    @Operation(summary =  "粉丝分页列表", description = "粉丝分页列表")
    public ServerResponseEntity<IPage<MyFriendVo>> fansPage(@Valid PageParam page, @RequestParam String usId,@RequestParam String currentId){
        //刷新关注消息 为已读
        if(StrUtil.isEmpty(usId) || currentId.equals(usId)){
            List<NotifyLog> records = notifyLogService.list(
                    new LambdaQueryWrapper<NotifyLog>()
                            .eq(NotifyLog::getRemindId, currentId)
                            .eq(NotifyLog::getType,4)
                            .eq(NotifyLog::getRemindType, 3));
            records.forEach(record -> record.setStatus(1));
            if (CollectionUtils.isNotEmpty(records)) {
                notifyLogService.updateBatchById(records);
            }
        }
        IPage<MyFriendVo> myFriendVoIPage = friendService.fansPage(page, usId, currentId);
        List<MyFriendVo> records = myFriendVoIPage.getRecords();
        if(ObjectUtil.isNull(records) || records.size()==0){
            return ServerResponseEntity.success(myFriendVoIPage);
        }
        List<String> userids = records.stream().map(s -> s.getId()).collect(Collectors.toList());
        List<UserSecurityConfig> list = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, userids));
        Map<String, UserSecurityConfig> userMap = list.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
        List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, currentId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, userids));
        Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        records.stream().forEach(myFriendVo->{//添加是否对自己开通私聊
            UserSecurityConfig userSecurityConfig = userMap.get(myFriendVo.getId());
            myFriendVo.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
            if (StringUtils.isNotEmpty(remarkMap.get(myFriendVo.getId()))) {
                myFriendVo.setUserName(remarkMap.get(myFriendVo.getId()));
            }
        });
        return ServerResponseEntity.success(myFriendVoIPage);
    }
    /**
     *
     * @param page
     * @param currentId
     * @return
     */
    @GetMapping("/fansPageSearch")
    @Operation(summary =  "粉丝分页列表", description = "粉丝分页列表")
    public ServerResponseEntity<IPage<MyFriendVo>> fansPageSearch(@Valid PageParam page,@RequestParam("currentId") String currentId, String userName, String groupId){
        return ServerResponseEntity.success(friendService.fansPageSearch(page, currentId, userName, groupId));
    }
    /**
     *
     * @param page
     * @param usId 为空代表用户自己的粉丝列表 不为空代表 当前访问用户的粉丝列表
     * @param currentId
     * @return
     */
    @GetMapping("/fansNotNotifyPage")
    @Operation(summary =  "粉丝分页列表", description = "粉丝分页列表")
    public ServerResponseEntity<IPage<MyFriendVo>> fansNotNotifyPage(@Valid PageParam page, String usId,@RequestParam String currentId){
        return ServerResponseEntity.success(friendService.fansPage(page, usId,currentId));
    }

    /**
     *
     * @param page
     * @param usId 为空代表用户自己的关注列表 不为空代表 当前访问用户的关注列表
     * @param currentId
     * @return
     */
    @GetMapping("/followPage")
    @Operation(summary =  "关注分页列表", description = "关注分页列表")
    public ServerResponseEntity<IPage<MyFriendVo>> followPage(@Valid PageParam page, String usId,@RequestParam String currentId){
        IPage<MyFriendVo> myFriendVoIPage = friendService.followPage(page, usId, currentId);
        List<MyFriendVo> records = myFriendVoIPage.getRecords();
        if(ObjectUtil.isNull(records) || records.size()==0){
            return ServerResponseEntity.success(myFriendVoIPage);
        }
        List<String> userids = records.stream().map(s -> s.getId()).collect(Collectors.toList());
        List<UserSecurityConfig> list = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, userids));
        Map<String, UserSecurityConfig> userMap = list.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
        List<MeltCloudUserRemark> remarkList = userRemarkService.list(Wrappers.lambdaQuery(MeltCloudUserRemark.class).eq(MeltCloudUserRemark::getUserId, currentId).eq(MeltCloudUserRemark::getType, 1).in(MeltCloudUserRemark::getObjId, userids));
        Map<String, String> remarkMap = remarkList.stream().collect(Collectors.toMap(MeltCloudUserRemark::getObjId, MeltCloudUserRemark::getRemark));
        records.stream().forEach(myFriendVo->{//添加是否对自己开通私聊
            UserSecurityConfig userSecurityConfig = userMap.get(myFriendVo.getId());
            myFriendVo.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
            if (StringUtils.isNotEmpty(remarkMap.get(myFriendVo.getId()))) {
                myFriendVo.setUserName(remarkMap.get(myFriendVo.getId()));
            }
        });
        return ServerResponseEntity.success(myFriendVoIPage);
    }
    /**
     *
     * @param page
     * @param currentId
     * @return 我的朋友列表 互关的人
     */
    @GetMapping("/myFriendListPage")
    @Operation(summary =  "粉丝分页列表", description = "粉丝分页列表")
    public ServerResponseEntity<IPage<MyFriendVo>> myFriendListPage(@Valid PageParam page,String usId, @RequestParam String currentId,String userName){
        IPage<MyFriendVo> myFriendVoIPage = friendService.myFriendListPage(page, usId, currentId, userName);
        List<MyFriendVo> records = myFriendVoIPage.getRecords();
        if(ObjectUtil.isNull(records) || records.size()==0){
            return ServerResponseEntity.success(myFriendVoIPage);
        }
        List<String> userids = records.stream().map(s -> s.getId()).collect(Collectors.toList());
        List<UserSecurityConfig> list = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, userids));
        Map<String, UserSecurityConfig> userMap = list.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
        records.stream().forEach(myFriendVo->{//添加是否对自己开通私聊
            UserSecurityConfig userSecurityConfig = userMap.get(myFriendVo.getId());
            myFriendVo.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
        });
        return ServerResponseEntity.success(myFriendVoIPage);

    }

    @Operation(summary =  "和当前人粉丝关系回显", description = "0: 关注 1：回关 2：已关注 3：互相关注")
    @GetMapping("/getRelation")
    public ServerResponseEntity getRelation(@RequestParam String currentId ,@RequestParam String usId){
        int relation = friendService.getRelation(usId, currentId);
        return ServerResponseEntity.success(relation);
    }

    @GetMapping("/searchUserListPage")
    @Operation(summary =  "搜索用户", description = "搜索用户")
    public ServerResponseEntity<IPage<MyFriendVo>> searchUserListPage(@Valid PageParam page, @RequestParam String currentId,String userName){
        IPage<MyFriendVo> myFriendVoIPage = friendService.searchUserListPage(page, currentId, userName);
        List<MyFriendVo> records = myFriendVoIPage.getRecords();
        if(ObjectUtil.isNull(records) || records.size()==0){
            return ServerResponseEntity.success(myFriendVoIPage);
        }
        List<String> userids = records.stream().map(s -> s.getId()).collect(Collectors.toList());
        List<UserSecurityConfig> list = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, userids));
        Map<String, UserSecurityConfig> userMap = list.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
        records.stream().forEach(myFriendVo->{//添加是否对自己开通私聊
            UserSecurityConfig userSecurityConfig = userMap.get(myFriendVo.getId());
            myFriendVo.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
        });
        return ServerResponseEntity.success(myFriendVoIPage);
    }

    @GetMapping("/recommend")
    @Operation(summary =  "推荐分页列表", description = "推荐分页列表")
    public ServerResponseEntity<IPage<MyFriendVo>> recommendList(@Valid PageParam page,String userName ,@RequestParam String currentId){
        IPage<MyFriendVo> myFriendVoIPage = friendService.recommendList(page, userName ,currentId);
        List<MyFriendVo> records = myFriendVoIPage.getRecords();
        if(ObjectUtil.isNull(records) || records.size()==0){
            return ServerResponseEntity.success(myFriendVoIPage);
        }
        List<String> userids = records.stream().map(s -> s.getId()).collect(Collectors.toList());
        List<UserSecurityConfig> list = userSecurityConfigService.list(new LambdaQueryWrapper<UserSecurityConfig>().in(UserSecurityConfig::getUserId, userids));
        Map<String, UserSecurityConfig> userMap = list.stream().collect(Collectors.toMap(UserSecurityConfig::getUserId, Function.identity()));
        records.stream().forEach(myFriendVo->{//添加是否对自己开通私聊
            UserSecurityConfig userSecurityConfig = userMap.get(myFriendVo.getId());
            myFriendVo.setMassageSwitch(friendService.getPrivacyTypeValue(Integer.valueOf(myFriendVo.getStatus()),userSecurityConfig.getPrivacyType()));
        });
        return ServerResponseEntity.success(myFriendVoIPage);
    }
    @GetMapping("/followRecommend")
    @Operation(summary =  "一键关注推荐分页列表", description = "批量推荐分页列表")
    public ServerResponseEntity followRecommend(@Valid PageParam page,String userName,@RequestParam String currentId){
        IPage<MyFriendVo> myFriendVoIPage = friendService.recommendList(page, userName, currentId);
        List<MyFriendVo> records = myFriendVoIPage.getRecords();
        friendService.followRecommend(records,currentId);
        return ServerResponseEntity.success();
    }


}
